<template>
  <div class="dashboard">
    <!-- 总销售额卡片 -->
    <div class="card">
      <div class="card-header">
        <span>订单总销售额</span>
        <el-tooltip effect="light" content="这里是总销售额的说明" placement="right">
          <i class="el-icon-question"></i>
        </el-tooltip>
      </div>
      <div class="card-body">
        <!-- 修改部分：使用 toFixed(2) 格式化总销售额 -->
        <span class="amount">￥{{ totalSales.toFixed(2) }}</span>
        <div class="comparison">
          <!-- 修改部分：使用 toFixed(2) 格式化周同比和日同比增长率 -->
          <span>周同比{{ weekGrowth.toFixed(2) }}%</span>
          <span class="arrow" :class="{ 'down': weekGrowth > 0, 'up': weekGrowth < 0 }"></span>
          <span>日同比{{ dayGrowth.toFixed(2) }}%</span>
          <span class="arrow" :class="{ 'down': dayGrowth > 0, 'up': dayGrowth < 0 }"></span>
        </div>
        <!-- 修改部分：使用 toFixed(2) 格式化日销售额 -->
        <span class="sub-text">日销售额 ￥{{ dailySales.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 会员注册量卡片 -->
    <div class="card">
      <div class="card-header">
        <span>会员注册量</span>
      </div>
      <div class="card-body">
        <span class="amount">{{ totalVisits }}位</span>
        <div id="visitsChart"></div>
        <span class="sub-text">当月注册量 {{ dailyVisits }}位</span>
      </div>
    </div>

    <!-- 支付笔数卡片 -->
    <div class="card">
      <div class="card-header">
        <span>客户总数</span>
      </div>
      <div class="card-body">
        <span class="amount">{{ totalPayments }}位</span>
        <div id="paymentsChart"></div>
        <!-- 修改部分：使用 toFixed(2) 格式化会员转化率 -->
        <span class="sub-text">会员转化率 {{ conversionRate.toFixed(2) }}%</span>
      </div>
    </div>


    <!-- 客户活跃度卡片 -->
    <div class="card">
      <div class="card-header">
        <span>客户活跃度</span>
        <el-badge value="实时" type="warning" effect="dark"/>
      </div>
      <div class="card-body">
        <div class="metrics-grid">
          <div class="metric-item">
            <span class="label">订单完成率</span>
            <span class="value">{{ activeData.orderCompletion }}%</span>
          </div>
          <div class="metric-item">
            <span class="label">月留存率</span>
            <span class="value">{{ activeData.customerRetention }}%</span>
          </div>
        </div>
        <div id="activityChart"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, watchEffect, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { Get_vip_Tolist,Get_vip_Order } from '@/api/customerVip/index';
import { Get_Customers } from '@/api/customer/index';
import dayjs from 'dayjs' // 添加dayjs库

const date = reactive({
  isFirst: true,
  data: [],
  Products: [],
  loading: false,
  key: '',
  details_key: '',
  details_key_id: '',
  pages: {
    page: 1,
    limit: 10,
    total: 0,
  },
});

const methods = {
  async bind() {
    const res = await Get_vip_Tolist();
    if (res.code === 0) {
      totalVisits.value = res.data.data[0].count;
      dailyVisits.value = res.data.data[0].addmonth;
    }
  },

  async bind2() {
    const res = await Get_Customers({
      page: date.pages?.page || 1,
      limit: date.pages?.limit || 16,
      key: date.key || '',
    });
    if (res.code === 0) {
      totalPayments.value = res.data.data.filter(c => ![0].includes(c.status)).length;
      // 修改部分：使用 toFixed(2) 格式化会员转化率
      conversionRate.value = parseFloat((res.data.record / res.data.data.filter(c => ![0].includes(c.status)).length * 100).toFixed(2));
      console.log(res.data.record);
    }
  },

  async bindSales() {
    try {
      const res = await Get_vip_Order({
        id:""
      });
      if (res.code === 0) {
        // 修改部分：检查数组是否为空
        const orders = res.data.data.length > 0 ? res.data.data : [];
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000);
        const thisWeekStart = new Date(todayStart.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000);
        const lastWeekStart = new Date(thisWeekStart.getTime() - 7 * 24 * 60 * 60 * 1000);

        let totalSalesAmount = 0;
        let dailySalesAmount = 0;
        let thisWeekSalesAmount = 0;
        let lastWeekSalesAmount = 0;
        let yesterdaySalesAmount = 0;

        orders.forEach((order: any) => {
          const orderDate = new Date(order.createTime);
          totalSalesAmount += order.money;
          if (orderDate >= todayStart) {
            dailySalesAmount += order.money;
          }
          if (orderDate >= thisWeekStart) {
            thisWeekSalesAmount += order.money;
          }
          if (orderDate >= lastWeekStart && orderDate < thisWeekStart) {
            lastWeekSalesAmount += order.money;
          }
          if (orderDate >= yesterdayStart && orderDate < todayStart) {
            yesterdaySalesAmount += order.money;
          }
        });

        // 修改部分：使用 toFixed(2) 格式化总销售额
        totalSales.value = parseFloat(totalSalesAmount.toFixed(2));
        // 修改部分：使用 toFixed(2) 格式化日销售额
        dailySales.value = parseFloat(dailySalesAmount.toFixed(2));
        // 修改部分：使用 toFixed(2) 格式化周同比增长率
        weekGrowth.value = parseFloat((lastWeekSalesAmount === 0 ? 0 : ((thisWeekSalesAmount - lastWeekSalesAmount) / lastWeekSalesAmount * 100)).toFixed(2));
        // 修改部分：使用 toFixed(2) 格式化日同比增长率
        dayGrowth.value = parseFloat((yesterdaySalesAmount === 0 ? 0 : ((dailySalesAmount - yesterdaySalesAmount) / yesterdaySalesAmount * 100)).toFixed(2));
      }
    } catch (error) {
      console.error('获取已支付订单数据失败:', error);
    }
  },
};

// 在script setup部分添加
const activeData = reactive({
  orderCompletion: 0,  // 订单完成率（来自Get_vip_Order）
  customerRetention: 0, // 客户留存率（来自Get_Customers）
  complaintRate: 0     // 投诉率（来自Get_Customer_Details）
});

// 在methods对象中添加
const bindActivity = async () => {
  // 订单完成率计算
  const ordersRes = await Get_vip_Order({ id: "" });
  if (ordersRes.code === 0) {
    // 使用payment字段代替status字段
    const validOrders = ordersRes.data.data.filter((order: any) =>
      Number(order.payment) === 1  // 1表示已支付
    );
    activeData.orderCompletion = Number(
      (validOrders.length / ordersRes.data.data.length * 100).toFixed(2)
    );
  }

  // 客户留存率计算（简化示例）
  const customersRes = await Get_Customers({ page: 1, limit: 100 });
  if (customersRes.code === 0) {
    // 新增：过滤无效客户作为总数
    const filteredCustomers = customersRes.data.data.filter(c => ![0, 2].includes(Number(c.status)));

    const activeCustomers = filteredCustomers.filter((c: any) => {
      // 添加空值保护和时间计算
      const nextTime = c.next_time || dayjs().format();
      return dayjs().diff(dayjs(nextTime), 'day') <= 30;
    });

    activeData.customerRetention = Number(
      (activeCustomers.length / filteredCustomers.length * 100).toFixed(2)
    );
  }
};

// 在watchEffect中添加方法调用
watchEffect(() => {
  methods.bind();
  methods.bind2();
  methods.bindSales();
  bindActivity(); // 新增
});

// 模拟数据
const totalSales = ref(0);
const weekGrowth = ref(0);
const dayGrowth = ref(0);
const dailySales = ref(0);

const totalVisits = ref(10);
const dailyVisits = ref(14);
const dayMode = ref(true);

const totalPayments = ref(60);
const conversionRate = ref(60);
const monthMode = ref(true);

const activityEffect = ref(78);
const weekActivityGrowth = ref(12);
const dayActivityGrowth = ref(-11);
const weekMode = ref(true);

// 在setup顶部添加计时器引用
const chartTimers = ref<NodeJS.Timeout[]>([]);

// 创建独立的图表初始化方法
const initVisitsChart = () => {
  const chart = echarts.init(document.getElementById('visitsChart'));
  const update = async () => {
    await methods.bind();
    chart.setOption({ /* 保持原有visitsOption配置 */ });
  };
  chartTimers.value.push(setInterval(update, 30000));
};

const initPaymentsChart = () => {
  const chart = echarts.init(document.getElementById('paymentsChart'));
  const update = async () => {
    await methods.bind2();
    chart.setOption({ /* 保持原有paymentsOption配置 */ });
  };
  chartTimers.value.push(setInterval(update, 30000));
};

const initActivityChart = () => {
  const chart = echarts.init(document.getElementById('activityChart'));
  const update = async () => {
    await bindActivity();
    chart.setOption({
      series: [{
        data: [{ value: activityEffect.value }]
      }]
    });
  };
  chartTimers.value.push(setInterval(update, 30000));
};

// 修改onMounted部分
onMounted(() => {
  initVisitsChart();
  initPaymentsChart();
  initActivityChart();
});

// 添加onUnmounted清理
onUnmounted(() => {
  chartTimers.value.forEach(timer => clearInterval(timer));
  chartTimers.value = [];
});
</script>

<style scoped>
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.metric-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
}

.label {
  display: block;
  color: #6c757d;
  font-size: 14px;
}

.value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}
.dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
}

.card {
  background-color: #ffffff;
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.card-body {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.amount {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333333;
}

.comparison {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 10px;
}

.arrow {
  display: inline-block;
  width: 0;
  height: 0;
  border-style: solid;
}

.up {
  border-width: 5px 4px 0 4px;
  border-color: #f56c6c transparent transparent transparent;
}

.down {
  border-width: 0 4px 5px 4px;
  border-color: transparent transparent #67c23a transparent;
}

.sub-text {
  color: #606266;
  font-size: 16px;
}
</style>
